package com.s69.appback.service;

import com.s69.appback.entity.AppCategory;
import com.s69.appback.mapper.AppCategoryDao;
import com.s69.appback.vo.TreeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class AppCategoryService {
    @Autowired
    AppCategoryDao appCategoryDao;

    public TreeVo getTree() {
        TreeVo tree=new TreeVo();
        List<TreeVo> vos=new ArrayList<>();
        List<AppCategory> list = appCategoryDao.queryAllBy(new AppCategory());
        for (AppCategory appCategory : list) {
            TreeVo treeVo=new TreeVo();
            BeanUtils.copyProperties(appCategory,treeVo);
            vos.add(treeVo);
        }
        for (TreeVo treeVo : vos) {
            if (treeVo.getParentid()==null){
                tree=findChildren(treeVo,vos);
            }
        }
        return tree;
    }

    private TreeVo findChildren(TreeVo vo, List<TreeVo> vos) {
        vo.setChildren(new ArrayList<>());
        for (TreeVo treeVo : vos) {
            if (vo.getId()==treeVo.getParentid()){
                vo.getChildren().add(treeVo);
                findChildren(treeVo,vos);
            }
        }
        return vo;
    }
}
